﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using iTransact.Utils;

namespace iTransact.Xml
{
	public static class GatewayXml
	{
		public static string GenerateGatewayXml(string username, string targetGateway, string key, XElement payload)
		{
			var document = new XDocument();
			var payloadSignature = PayloadSignature.Generate(payload.ToString(SaveOptions.DisableFormatting), key);

			document.Add(
				new XElement("GatewayInterface",
					new XElement("APICredentials",
						new XElement("Username", username),
						new XElement("PayloadSignature", payloadSignature),
						new XElement("TargetGateway", targetGateway)
					), payload // Add the payload here
				)
			);

			var output = new StringBuilder();
			var writer = XmlWriter.Create(output);
			document.WriteTo(writer);
			writer.Flush();
			writer.Close();

			// iTransact doesn't use Encoding
			return output.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<?xml version=\"1.0\"?>").ToString();
		}
	}
}
